package com.boot.interceptor;

import com.alibaba.fastjson.JSON;
import com.boot.entity.TUser;
import com.boot.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Chunsheng.Zhang
 * @date 2021/1/6 16:51
 * @description : TODO
 */
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JWTUtil jwtUtil ;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {


        // Token 验证
        String token = request.getHeader(jwtUtil.getHeader());
        if(StringUtils.isEmpty(token)){
            throw new Exception(jwtUtil.getHeader()+ "不能为空");
        }
        Claims claims = jwtUtil.getTokenClaim(token);
        if(claims == null || jwtUtil.isTokenExpired(claims.getExpiration())){
            throw new Exception(jwtUtil.getHeader() + "失效，请重新登录");
        }


        //设置 claims中获取到user放入request对象中，以便后面的接口获取到当前登录用户
        TUser user = JSON.parseObject(claims.getSubject(), TUser.class);
        request.setAttribute("currentUser", user);
        return true;
    }
}